
package com.kweative.cluster;

import com.kweative.util.ByteUtil;
import com.sun.xml.internal.ws.util.ByteArrayBuffer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
public class Transmitter extends Transceiver {
    private Stack<ActionPackage> queue = new Stack<ActionPackage>();
    private boolean running = false;

    public Transmitter() {
        super();
    }
    public void transmit(Action a) {
        ActionPackage ap = new ActionPackage(Cluster.node());
        transmit(ap);
    }
    public void transmit(ActionPackage ap) {
        try {
            DatagramSocket s = new DatagramSocket();
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bout);
            out.writeObject(ap);
            byte[] output = bout.toByteArray();
            s.send(new DatagramPacket(output,output.length,InetAddress.getByName(Cluster.instance().getGroup()),Cluster.instance().getPort()));
        } catch (IOException ex) {
            Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    @Override
    public void run() {
        ClusterNode node = new ClusterNode();
        Cluster.instance().setCurrentNode(node);
        Cluster.nodes().push(node);
        addToQueue(new Action(Action.ActionType.GREET,node,null));
        running = true;
        while(running) {
            if(queue.size() > 0) {
                ActionPackage ap = queue.pop();
                transmit(ap);
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Transmitter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        transmit(new Action(Action.ActionType.LEAVE,null,null));
    }

    public void addToQueue(ActionPackage ap) {
        queue.push(ap);
    }
    public void addToQueue(Action a) {
        ActionPackage ap = new ActionPackage(Cluster.node());
        ap.push(a);
        addToQueue(ap);
    }

}
